// pages/trouble/trouble.js
const app = getApp();
var adds = {};

Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    //UserName: app.globalData.userInfo,
    //cvalue: [],
    //picker: [],
    img_arr:[],
    formdata: '',
    dex:0,
    logState:0,
    //输入用数据
    showInputStatus: false,
    inputValue: '',//点击结果项之后替换到文本框的值  上传人的前端文本值
    adapterSource: [],//本地匹配源 大小写要tolowercasea
    bindSource: [],//绑定到页面的数据，根据用户输入动态变化
    personId: '未能获得上传人id',  //上传人id
    //车站标段
    station:[['a','b'], ['b','c'], ['c', 'd']],
    parts:['1','2','3'],
    siteIds: [['A', 'B'], ['B', 'C'], ['C', 'D']],
    select:[],
    coldex:0,
    //userNickName:'xxx'
    UploadName: app.globalData.userName,
    UploadWork: app.globalData.userWork,
    UploadId: app.globalData.userId,
    OpenId: app.globalData.openid,
    creat: app.globalData.UserName
  },
  formSubmit: function (e) {  //!e.detail.value.category ||
    if ( this.data.img_arr.length == 0 || this.data.personId == null) {
      wx.showToast({
        title: '请填写所有信息',
        icon: 'loading',
        duration: 3000
      });
    }
    else {
      console.log('form发生了submit事件，携带数据为：', e.detail.value);
      //e.detail.value.siteId = this.data.cvalue[e.detail.value.siteId[1]];
      //e.detail.value.siteId = e.detail.value.siteId[1]
      e.detail.value.siteId = this.data.siteIds[e.detail.value.siteId[0]][e.detail.value.siteId[1]]
      console.log('改变siteId', e.detail.value);
      var id = e.target.id;
      console.log('person', this.data.UploadId)//personId)
      e.detail.value.reportPerson = this.data.UploadId;//personId;
      adds = e.detail.value;
      adds.creator=this.data.creat;
      //this.setData({ formdata: adds });

      console.log('验证用户');
      this.checkLog();  //验证加上传
      console.log("log", this.data.logState,adds) 
    }
    /*if (this.data.logState == 0) {//不在登录状态要重新登录
      console.log("log", this.data.logState)
      console.log("no name");
      wx.navigateTo({
        url: '/pages/auth/auth',
      });
    }*/
          
  },
  
  checkLog:function(){
    let that=this;
    wx.checkSession({
      success: function (res) {
        console.log(res, '登录未过期')    
        that.data.logState=1;
        console.log("suclog", that.data.logState);
        if (that.data.logState == 1) {    //处于登录状态下则上传
              console.log("log", that.data.logState)
              console.log(app.globalData.userInfo);             
              that.upload();            
          }        
      },
      fail: function (res) {
        console.log(res, '登录过期了')
        wx.showToast({  //Modal
          title: '你的登录信息过期了，请重新登录',
          icon: 'loading',
          duration: 1000
        })
        that.data.logState = 0; 
        console.log("failog", that.data.logState)
        console.log("no name");
        wx.navigateTo({
          url: '/pages/auth/auth',
        });
      },
    });
  },

  upload: function () {
    var that = this;
    console.log("trouble upload")
    if (this.data.img_arr.length==0){
      console.log("function upload")
      wx.request({
        header: {
          "Content-Type": "application/json"
          //"Content-Type": "multipart/form-data; charset=utf-8"
        },  
        url:'http://10.10.11.173:8989/hidden/insertHiddenDanger',
        //url: 'http://localhost:9090/course/hidden/uploadPic',
        data:adds,
        method:'POST',
        success: function (res) {
          console.log('up res',res);
                 
        },
        fail: function (res) {
          console.log("up fail", res);
        },
      });      
    }
    else this.upImgs(); 
    
  },

upImgs:function(){  //提交表单时候调用的
  var that=this;
  console.log("upimgs",adds)
  if (that.data.img_arr.length != 0)
    for (var i = 0; i < that.data.img_arr.length; i++) {
      adds.picNum = 'pic' + i;  //给表单信息加一个属性用来命名图片
      wx.uploadFile({
        url: 'http://10.10.11.195:8080/szgd/weChat/reportHiddenDanger',//10.10.11.173:8989/hidden/uploadPic',
        //url:'http://localhost:9090/course/hidden/uploadPic',
        header: {
          "Content-Type": "application/json"
        },
        filePath: that.data.img_arr[i],
        name: 'file',
        formData: adds,//JSON.stringify(adds),//adds,//
        success: function (res) {
          console.log('pic res',res);
          if (res) {
            wx.showToast({
              title: '已提交发布！',
              duration: 3000
            });
          }
        },
        fail: function (res) {
          console.log("pic fail", res);
        },
      })
    }

  that.setData({
    formData: ''
  })
},

  upimg: function () {  //上传图片
    var that = this;
    let len = 0;
    if (that.data.img_arr != null) { //防止欺骗系统多上传
      len = that.data.img_arr.length;
    };//获取当前已有的图片
    if (this.data.img_arr.length < 1) {  //3   3-len
      wx.chooseImage({
        count:1-len,    //3-len
        sizeType: ['original', 'compressed'],
        success: function (res) {
          console.log(len);          
          that.setData({
            img_arr: that.data.img_arr.concat(res.tempFilePaths)
          })
        }
      })
    } else {
      wx.showToast({
        title: '最多上传一张图片',//3
        icon: 'loading',
        duration: 3000
      });
    }
  }, 
  clear:function(event){ //取消上传
    console.log(event)  //是关闭图案的
    const nowIndex = event.currentTarget.dataset.id;
    let img_arr = this.data.img_arr;
    img_arr.splice(nowIndex, 1);
    this.setData({
      img_arr
    })
  },
  preview(event) {  //预览图片
    const nowIndex = event.currentTarget.dataset.id;
    const img_arr = this.data.img_arr;
    wx.previewImage({
      current: img_arr[nowIndex],  //当前预览的图片
      urls: img_arr,  //所有要预览的图片
    })
  },
  formReset: function (e) {  //清空所有图片
    console.log(e)
    var that = this;
    that.setData({ img_arr: [], index: null});
  },
  /*PickerChange(e) {
    console.log('Change',e);
    console.log(this.data.cvalue[e.detail.value]);
    this.setData({
      dex: e.detail.value
    })
  },*/
  PickerChange(e) {
    console.log("pick", e)
    console.log('Change', e.detail.value);
    let undex=e.detail.value[1] //第二个数组的下标
    let updex = e.detail.value[0] //第一个数组的下标
    console.log("upn",updex,undex)
    console.log(this.data.station[updex][undex]);
    let station = this.data.station[updex][undex];//.name
    this.setData({
      dex: station
    })
    //this.data.coldex=0;
  },
  MultiColumnChange(e) {
    console.log("mulchange", e.detail);
    let coldex = this.data.coldex
    let datum = {      //两个相关联的数组
      parts: this.data.parts,
      station: this.data.station[coldex]
    };
    
    console.log("arrays", datum.station, datum.parts);
    if(e.detail.column==0){   //滑动第一列时  第二列需要变化
      this.data.coldex = e.detail.value;
      coldex=this.data.coldex    
      datum.station = this.data.station[coldex]  
      console.log("roll",this.data.coldex,datum.station)
    } else if (e.detail.column == 1){
      console.log("row",coldex,"col",e.detail.value,datum.station[e.detail.value])
      //datum.station = this.data.station[coldex] 
    }
    let sel=[datum.parts,datum.station]
    console.log("Sel",sel)
    this.setData({ select: sel })
  },

 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {  //获取设备类型
    let that = this;
    let _custom = wx.getMenuButtonBoundingClientRect()
    setTimeout(() => {
      if (that.data.CustomBar === 'undefined' || typeof (that.data.CustomBar === 'undefined')) {
        let new_custom = _custom
        that.setData({
          CustomBar: new_custom.bottom + new_custom.top - that.data.StatusBar
        })
      }
    }, 800);

    /*wx.request({
      //url: 'http://localhost:9090/course/getDict?TNAME=HD_TYPE',
      url:'http://10.10.11.173:8989/getDict?TNAME=HD_TYPE',
      header: {
        "Content-Type": "application/json"
      }, 
      success: function (res) {
        console.log(res);
        var sindex = new Array();
        var spicker = new Array();
        for(var i=0;i<res.data.length;i++){
          sindex.push(res.data[i].cvalue);
          spicker.push(res.data[i].mean);
            
          // that.setData({    
          //   ["picker[" + i+"]"]:res.data[i].mean
          // })
        }
              
        that.setData({ picker: spicker, cvalue: sindex });
        console.log(sindex);
        console.log(spicker);  
        console.log(that.data.cvalue);
        console.log(that.data.picker);  
      },
      fail: function (res) {
        console.log("fail", res);
      },
    });*/
    //多条选择picker 10.10.11.195:8080/project/getBidAndSite
    wx.request({  //车站标段
      url: 'http://10.10.11.195:8080/szgd/weChat/getBidAndSite',
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        console.log("bandS",res);
        that.data.parts=res.data.bid; //标段数组
        that.data.station=res.data.site;  //车站名称数组
        that.data.siteIds=res.data.siteId;  //车站id数组
        let tempSta=res.data.site[0];   //取第一个元素初始化，但是data里面的还是全部的
        that.setData({ select: [that.data.parts, tempSta]});
        console.log("select", that.data.select, that.data.station, that.data.siteIds);
        
      }
    });
    let parts = that.data.parts;
    let station = that.data.station[0];
    that.setData({ select: [parts, station] });
    console.log("select", that.data.select, that.data.station);

    console.log("pp", that.data.People, this.data.adapterSource)
    this.data.People = app.globalData.People;
    let names = []
    this.data.People.forEach(function (value) {
      names.push(value.NAME);
    });
    console.log(names);
    this.data.adapterSource = this.data.People;// names;
    console.log("pp", that.data.People, this.data.adapterSource)
    //用户名
    //this.data.UserName = app.globalData.userInfo
    // this.setData({ userNickName: app.globalData.userInfo.nickName})
    let userName = app.globalData.UserName
    let userId = app.globalData.userId
    let creator=userName
    
    this.setData({
      UploadName: app.globalData.userName,
      UploadWork: app.globalData.userWork,
      UploadId: userId,
      creat:creator
      });
    console.log("nick",this.data.userNickName,this.data.UploadId,this.data.UploadName,this.data.UploadWork,userName)
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})